﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRGeometry;

namespace YJKDimensionModel.ArrowDimension
{
	internal class ArrowDimArrow
	{
		public static void FindAndModifyArrow(UIDocument UIDoc, Document doc, ArrowDimData data, List<XYZ> LstPickPoint, bool ifNeedTrans = true)
		{
			Transform aviewTransform = ArrowDimTempFamily.GetAViewTransform(UIDoc.ActiveView);
			XYZ xyz = Geometry.TransformPoint(LstPickPoint[0], aviewTransform) - Geometry.TransformPoint(LstPickPoint[1], aviewTransform);
			Line line = null;
			double num = (-XYZ.BasisX).AngleTo(xyz);
			if (xyz.Y > 0.0)
			{
				line = Line.CreateBound(XYZ.Zero, -XYZ.BasisZ);
			}
			else
			{
				line = Line.CreateBound(XYZ.Zero, XYZ.BasisZ);
			}
			if (data.StrArrowAngle.Contains("°"))
			{
				data.StrArrowAngle = data.StrArrowAngle.Substring(0, data.StrArrowAngle.Length - 1);
			}
			Element element = null;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfCategory(BuiltInCategory.OST_GenericAnnotation);
			foreach (Element element2 in filteredElementCollector.WhereElementIsNotElementType())
			{
				if (element2.Name.Equals(data.StrArrowType))
				{
					element = element2;
					break;
				}
			}
			if (element != null)
			{
				using (Transaction transaction = new Transaction(doc, "GetArrow"))
				{
					try
					{
						transaction.Start();
						FamilyManager familyManager = doc.FamilyManager;
						IList<FamilyParameter> parameters = familyManager.GetParameters();
						for (int i = 0; i < parameters.Count; i++)
						{
							if (parameters[i].Definition.Name.Contains("角度"))
							{
								double num2 = Convert.ToDouble(data.StrArrowAngle);
								familyManager.Set(parameters[i], num2 * Math.PI / 180.0);
							}
						}
						ElementTransformUtils.RotateElement(doc, element.Id, line, num);
						if (xyz.X > 0.0 || (xyz.X == 0.0 && xyz.Y > 0.0))
						{
							XYZ normal = xyz.CrossProduct(XYZ.BasisZ);
							Plane plane = RevitVersionFuncs.CreatePlanByNormalAndOrigin(normal, XYZ.Zero);
							RevitVersionFuncs.MirrorElements(doc, new List<ElementId>
							{
								element.Id
							}, plane, false);
							if (UIDoc.Application.Application.VersionNumber == "2015")
							{
								doc.Delete(element.Id);
							}
						}
						transaction.Commit();
					}
					catch (Exception)
					{
						transaction.RollBack();
					}
				}
			}
		}
	}
}
